//
//  HDCoverageToolsOC.m
//  jdcomiphone
//
//  Created by 宋永建 on 2024/10/14.
//

#import "HDCoverageToolsOC.h"
#import "InstrProfiling.h"

@implementation HDCoverageToolsOC
+ (instancetype)shared {
    static HDCoverageToolsOC *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (void)registerCoverageWithModuleName:(NSString *)moduleName {
    NSString *name = [NSString stringWithFormat:@"%@.profraw", moduleName];
        NSLog(@"registerCoverage, moduleName: %@", moduleName);
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSError *error = nil;
        
        // 获取文档目录路径
        NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        if (!documentDirectory) {
            NSLog(@"Error fetching document directory: %@", error);
            return;
        }
        
        // 拼接文件路径
        NSString *filePath = [documentDirectory stringByAppendingPathComponent:name];
        NSLog(@"HDCoverageGather filePath: %@", filePath);
        
        // 调用 LLVM 覆盖率设置函数
        __llvm_profile_set_filename([filePath UTF8String]);
}

// 合适的时机代码覆盖率上报
- (void)saveAndUpload {
    __llvm_profile_write_file();
    NSLog(@"HDCoverageTools.shared.saveAndUpload");
}
@end
